package red.yancloud.www.ui.activity

import android.Manifest
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.util.Log
import android.view.ViewTreeObserver
import androidx.appcompat.app.AppCompatActivity
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_welcome.*
import red.yancloud.www.R
import red.yancloud.www.common.Constants
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.ui.dialog.PermissionObtainDialog
import red.yancloud.www.ui.listener.OnClickPermissionListener
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.TimeFormatUtil
import java.io.File

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/17 14:45
 * E_Mail：yh131412hys@163.com
 * Describe：欢迎页
 * Change：
 * @Version：V1.0
 */
class WelcomeActivity : AppCompatActivity() {

    private val TAG = "WelcomeActivity"

    private val filePath = Constants.ROOT_PATH + File.separator + "shuhai_welcome.png"
    private var isComplete = true
    private var num = 0

    internal var sendRunnable: Runnable = Runnable {
        try {
            Thread.sleep(3000)

            if (isComplete) {
                startMain()
            }
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_welcome)
        grantedPermission()

        initView()
    }

    private fun initView() {
        welcomeActivity_iv.setBackgroundResource(R.drawable.splash_load)
        val animation = welcomeActivity_iv.background as AnimationDrawable
        welcomeActivity_iv.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                animation.start()
                return true
            }
        })
    }

    internal var permissionListener: OnClickPermissionListener = object :
        OnClickPermissionListener {
        override fun permissionObtain() {
            grantedPermission()
        }
    }

    /**
     * 授予权限
     */
    private fun grantedPermission() {
        RxPermissions(this).requestEach(
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA
        ).subscribe(object :Consumer<Permission>{
                override fun accept(permission: Permission?) {
                    if (permission != null) {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            Log.e(TAG, permission.name + " is granted.");

                            num ++ ;
                            if (num==5) {

                                Thread(sendRunnable).start();
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.e(TAG, permission.name + " is denied. More info should be provided.");
                            PermissionObtainDialog(this@WelcomeActivity,permissionListener).show();
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.e(TAG, permission.name + " is denied.");
                            PermissionObtainDialog(this@WelcomeActivity,permissionListener).show();
                        }
                    }
                }
            });
    }

    /**
     * 打开主页面
     */
    private fun startMain() {

        val file = File(filePath)

        val intent = Intent()
        val cls: Class<*>
        if (file.exists() && TimeFormatUtil.getCurrentDateTimeSeconds() < UserInfoShardPreference.instance.splashTime) {

//            cls = DynamicWelcomeActivity::class.java
            cls = MainActivity::class.java
        } else {

//            if (UserInfoShardPreference.instance.getISShowLead(AppUtils.getAppVersionCode())) {
//                cls = SplashActivity::class.java
//            } else {
                cls = MainActivity::class.java
//            }
        }
        intent.setClass(this@WelcomeActivity, cls)
        startActivity(intent)
        finish()
    }
}
